import { Module } from 'vuex'

import {
  accountLoginRequest,
  getVertifyCodeRequest,
  requestUserInfoById,
} from '@/service/login/login'
import localCache from '@/utils/cache'

import router from '@/router'

import { IAccount } from '@/service/login/type'
import { ILoginState } from './types'
import { IRootState } from '../types'

import { h } from 'vue'
import { ElNotification } from 'element-plus'
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      vertifyCode: '',
      errMsg: '',
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: [],
    }
  },
  mutations: {
    changeVertifyCode(state, vertifyCode: string) {
      state.vertifyCode = vertifyCode
    },
    changeErrMsg(state, errMsg: string) {
      state.errMsg = errMsg
    },

    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, UserMenus: any) {
      state.userMenus = UserMenus
    },
  },
  getters: {},
  modules: {},
  actions: {
    async getVertifyCode({ commit }) {
      const vertifyCode = await getVertifyCodeRequest()
      commit('changeVertifyCode', vertifyCode)
    },

    async accountLoginAction({ commit, dispatch,state }, payload: IAccount) {
      //  console.log('执行accountLoginAction', payload)

      //1.实现登录逻辑
      const loginResult = await accountLoginRequest(payload)
      console.log(loginResult)

      if (loginResult.code == -1001) {
        commit('changeErrMsg', '密码错误')
      } else if (loginResult.code == -1002) {
        commit('changeErrMsg', '用户名或密码错误')
      } else if (loginResult.code == -1003) {
        commit('changeErrMsg', '验证码错误')
      } else {
        const res = loginResult.data
        if (res) {
          commit('changeErrMsg', '登录成功')
          commit('changeToken', res.token)
          localCache.setCache('token', res.token)
          localCache.setCache('user', JSON.stringify(res))
          router.push('/main')
        }
      }
      ElNotification({
        title: '提示',
        message: h('i', { style: 'color: teal' }, state.errMsg),
      })
    

      //
      //dispatch('getInitialDataAction', null, { root: true })
      //跳到 /main
    },
    async getUserInfoByID({ commit }, id: number) {
      const userInfo = await requestUserInfoById(id)
      commit('changeUserInfo', userInfo)
    },

    loadLocalLogin({ commit }) {
      console.log('loadLocaleLogin');
      
      const token = localCache.getCache('token')
      console.log('token',token);
      
      if (token) {
        commit('changeToken', token)
      }

      const user = localCache.getCache('user')
      if (user) {
        commit('changeUserInfo', user)
      }
    },
  },
}

export default loginModule
